/**
 * Created by tanbingqin on 2019/11/29.
 */
import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Tabs, Input, Row, Col, Modal, Popover, Button, Badge, Radio, message, Popconfirm, Select, Dropdown, Menu, Icon } from 'antd';
const TabPane = Tabs.TabPane;
const Option = Select.Option;
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import policyService from "containers/travel-standard/travel-standard.service"
import AdvancedTable from 'components/advanced-table'
const { SimpleTable } = AdvancedTable;
import Priority from 'components/template/priority'
import RuleDetail from 'containers/travel-standard/rule-detail'
import SlideFrame from 'components/slide-frame'
import NewScene from 'containers/travel-standard/new-scene'
import errorMessage from 'share/errorMessage'
import HotelConfig from 'containers/travel-standard/hotel-config'
import 'styles/custom-fields.scss'
import Importer from 'components/template/importer/index';
import ExportModal from 'components/template/export-modal/export-modal';
import Space from "components/space";

class TravelStandard extends React.Component{
  travelTypeMapping = {
    'flight': 1001,
    'train': 1002,
    'hotel': 1003,
    'car': 1008,
    'dining': 1010
  };
  constructor(props) {
    super(props);
    this.state = {
      isTenant: false, //是否是租户权限
      hotelTypeData: {}, //酒店配置的选择范围
      hotelConfigData: {}, //酒店配置数据
      hotelConfigId: '', //酒店配置的id
      participantRuleCode: '', //内部参与人多条标准时
      externalParticipantRuleCode: '', //外部参与人标准
      multiConsolidatedRuleCode: '', //多个参与人统一订票时
      multiConsolidatedRuleAmount: 100, //多个参与人统一订票时的百分比
      multiIndividualRuleCode: '', //多个参与人各自订票时
      tab: 'flight',
      searchForm: [
        {
          id: 'levelCode',
          label: messages('request-1.key726')/*层级*/,
          component: <Radio.Group>
            <Radio value="ALL">{messages('common.all')/*全部*/}</Radio>
            <Radio value="COMPANY">{messages('request-1.key725')/*公司*/}</Radio>
            <Radio value="SET_OF_BOOK">{messages('request-1.key743')/*帐套*/}</Radio>
          </Radio.Group>,
          initialValue: 'ALL',
          dataIndex: 'levelCode',
          parser: value => ({
            levelCode: value !== 'ALL' ? value : undefined
          }),
          tagParser: value => {
            if (value === 'ALL') {
              return messages('common.all')/*全部*/;
            } else {
              return value === "COMPANY" ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/;
            }
          }
        },
        {
          id: 'levelOrgId',
          dataIndex: 'levelName',
          label: messages('request-1.key727')/*所属组织*/,
          parser: value => ({
            levelOrgId: value ? (value.range === 'SET_OF_BOOK' ? value.rangeValue.setOfBooksId : value.rangeValue.id) : undefined
          }),
          tagParser: value => {
            if (value && value.range === 'SET_OF_BOOK') {
              return value.rangeValue.setOfBooksName;
            }
            if (value && value.range === 'COMPANY') {
              return value.rangeValue.name;
            }
          },
          component: <Priority onlySetOfBooks />,
        },
        {
          id: 'ruleName', label: messages('request-1.key326')/*名称*/, component: 'Input', dataIndex: 'comment',
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'name', label: messages('request-1.key326')/*名称*/, component: 'Input', dataIndex: 'name',
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'travelRuleCompanyList',
          label: messages('request-1.key744')/*启用公司*/,
          component: 'Chooser',
          props: {
            labelKey: 'name',
            valueKey: 'id',
            type: 'priority_company'
          },
          dataIndex: 'travelRuleCompanyList',
          parser: value => ({
            companyIds: value ? value.map(item => item.id) : undefined
          })
        }
      ],
      //机票，火车，酒店，用车的columns
      columns: [
        {
          title: messages('request-1.key726')/*层级*/,
          dataIndex: 'levelCode',
          render: (value, record) => {
            return value === "COMPANY" ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/
          }
        },
        {
          title: messages('request-1.key727')/*所属组织*/,
          dataIndex: 'levelName',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key744')/*启用公司*/,
          dataIndex: 'travelRuleCompanyList',
          width: '10%',
          render: (value,record) => (
            this.renderCompany(value, record)
          )
        },
        {
          title: messages('request-1.key326')/*名称*/,
          dataIndex: 'comment',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key745')/*适用人员*/,
          dataIndex: 'travelRuleRelations',
          width: '15%',
          render: (value,record) => (
            this.renderUser(value,record)
          )
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: 'status', width: '10%', align: "right",
          render: (value,record) => (
            <Badge
              status={value === 1001 ? 'success' : 'error'}
              text={value === 1001 ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            />
          )
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', key: 'operation', align: "center",
          render: (text, record) => (
            <span>
              {!record.readOnly && (
                <span>
                  <a onClick={(e) => this.handleNewEdit(e, record)}>{messages('common.edit.copy')/*复制并编辑*/}</a>
                  <span className="ant-divider"/>
                  <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('request-1.key386')/*你确认要删除？*/}>
                    <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a>
                  </Popconfirm>
                </span>
              )}
            </span>
          )
        }
      ],
      //用餐的columns
      columnsDining: [
        {
          title: messages('request-1.key726')/*层级*/,
          dataIndex: 'levelCode',
          render: (value, record) => {
            return value === "COMPANY" ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/
          }
        },
        {
          title: messages('request-1.key727')/*所属组织*/,
          dataIndex: 'levelName',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key326')/*名称*/,
          dataIndex: 'name',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key746')/*适用表单*/, dataIndex: 'visibleForms', width: '40%',
          render: (value, record) => {
            if (value && value.length) {
              let formNameList = [];
              value.map(form => {
                formNameList.push(form.formName);
              });
              return <Popover placement="topLeft" content={formNameList.join(',')}>{formNameList.join(',')}</Popover>
            } else {
              return <div>{messages('request-1.key735')/*通用*/}</div>
            }
          }
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: 'status', width: '10%', align: "right",
          render: (value, record) => (
            <Badge
              status={value === 1 ? 'success' : 'error'}
              text={value === 1 ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            />
          )
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', key: 'operation', align: "center",
          render: (text, record) => (
            <span>
              {!record.readOnly && (
                <Popconfirm onConfirm={(e) => this.handleDeleteDiningType(e, record)} title={messages('request-1.key386')/*你确认要删除？*/}>
                  <a onClick={(e) => {e.preventDefault(); e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a>
                </Popconfirm>
              )}
            </span>
          )
        }
      ],
      showImportModal: false,
      pagination: {},
      searchParams: {},
    }
    this.sceneDetail = menuRoute.getRouteItem('dining-detail', 'key');
  }

  componentWillMount() {
    const { currentMenuPermission } = this.props;
    this.getHotelTypes();
    this.getHotelTypesScope();
    this.initPriority(currentMenuPermission);
  };

  componentWillReceiveProps(nextProps) {
    const { currentMenuPermission } = nextProps;
    this.initPriority(currentMenuPermission);
  }

  //初始化权限
  initPriority = (currentMenuPermission) => {
    //是否是租户权限
    let isTenant = currentMenuPermission.currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyAll;
    this.setState({isTenant});
  };

  //获取酒店配置数据
  getHotelTypes = () => {
    policyService.getHotelConfig().then((resp) => {
      this.setState({
        hotelConfigData: resp.data,
        hotelConfigId: resp.data.levelCode === 'TENANT' ? resp.data.id : '', //后台根据是否有id区分新建还是编辑，tenant是id才是有用的值，system时id是系统的默认值，实际是没有租户值的配置
        participantRuleCode: resp.data.participantRule,
        externalParticipantRuleCode: resp.data.externalParticipantRule,
        multiConsolidatedRuleCode: resp.data.multiConsolidatedRule,
        multiConsolidatedRuleAmount: resp.data.multiRate ? resp.data.multiRate : 100,
        multiIndividualRuleCode: resp.data.multiIndividualRule
      });
    });
  };

  //获取酒店标准下拉框的选择范围数据
  getHotelTypesScope = () => {
    travelPolicyService.getHotelTypesScope().then((resp) => {
      this.setState({hotelTypeData: resp.data});
    });
  };

  //复制并编辑
  handleNewEdit = (e, record) => {
    e.preventDefault();
    e.stopPropagation();
    const { tab } = this.state;
    //复制要把id置空
    let resultRecord = JSON.parse(JSON.stringify(record));
    resultRecord.id = null;
    SlideFrame.open({
      title: messages('request-1.key747')/*新建标准*/,
      content: RuleDetail,
      afterClose: this.handleCloseSlide,
      params: {
        travelType: this.travelTypeMapping[tab],
        record: resultRecord
      }
    }, this);
  };

  //删除
  handleDelete = (e, record) => {
    travelPolicyService.deleteTravelStandardRule(record.id).then(resp => {
      if (resp.status === 200){
        message.success(messages('common.delete.successful')/*删除成功*/);
        this.simpleTableRef.getList(true, 1);
      }
    }).catch(e => {
      errorMessage(e.response);
    })
  };

  handleDeleteDiningType = (e, record) => {
    travelPolicyService.deleteDiningScene(record.id).then(res => {
      message.success(messages('common.delete.successful')/*删除成功*/);
      this.simpleTableRef.getList(true, 1);
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  //表格渲染启用公司
  renderCompany = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      if (value) {
        value.map((item, index) => {
          if (item.companyId) {
            relationNameList.push(item.companyName);
          }
        });
      }
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('request-1.key735')/*通用*/}</span>
    }
  };

  //表格渲染适用人员
  renderUser(value, record){
    if (value && value.length) {
      if (value[0].type === 1001){
        return <span>{messages('request-1.key735')/*通用*/}</span>
      }else {
        let relationNameList = [];
        if (value) {
          value.map((item, index) => {
            if (item.relationOID) {
              relationNameList.push(item.relationName);
            }
          });
        }
        return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
      }
    } else {
      return null;
    }
  };

  service = (page, pageSize, searchParams) => {
    const { tab } = this.state;
    let params = {
      page,
      size: pageSize,
      travelType: this.travelTypeMapping[tab] === 1010 ? undefined : this.travelTypeMapping[tab],
      ...searchParams
    };
    this.setState({
      searchParams: params
    })
    return policyService.getRuleList(params, this.travelTypeMapping[tab]);
  };

  importOfferFile = () => {
    this.simpleTableRef.getList();
  };

  handleTabChange = (tab) => {
    //先把tab重新置空，切换tab的时候重新加载dom
    this.setState({tab: ''}, () => {
      this.setState({tab});
    });
  };

  handleRowClick = (record) => {
    const { tab } = this.state;
    if (tab !== 'dining') {
      SlideFrame.open({
        title: messages('request-1.key748')/*编辑标准*/,
        content: RuleDetail,
        afterClose: this.handleCloseSlide,
        params: {
          travelType: this.travelTypeMapping[tab],
          record
        }
      }, this);
    } else {
      let url = '';
      url = this.sceneDetail.url.replace(':sceneId', record.id);
      this.context.router.push(url);
    }
  };

  handleNew = () => {
    const { tab } = this.state;
    if (tab !== 'dining') {
      SlideFrame.open({
        title: messages('request-1.key747')/*新建标准*/,
        content: RuleDetail,
        afterClose: this.handleCloseSlide,
        params: {
          travelType: this.travelTypeMapping[tab]
        }
      }, this);
    } else {
      SlideFrame.open({
        title: messages('request-1.key749')/*新建类型*/,
        content: NewScene,
        afterClose: this.handleCloseSlide,
        params: {
          travelType: this.travelTypeMapping[tab]
        }
      }, this);
    }
  };

  handleCloseSlide = (success) => {
    success && this.simpleTableRef.getList(true, 1);
  };

  handleEditHotelConfig = () => {
    const { hotelConfigId, hotelTypeData, participantRuleCode, externalParticipantRuleCode, multiConsolidatedRuleCode,
      multiConsolidatedRuleAmount, multiIndividualRuleCode
    } = this.state;
    SlideFrame.open({
      title: messages('request-1.key750')/*差标规则*/,
      content: HotelConfig,
      afterClose: this.handleCloseHotelSlide,
      params: {
        hotelConfigId,
        hotelTypeData,
        participantRuleCode,
        externalParticipantRuleCode,
        multiConsolidatedRuleCode,
        multiConsolidatedRuleAmount,
        multiIndividualRuleCode
      }
    }, this);
  };

  handleCloseHotelSlide = (success) => {
    success && this.getHotelTypes();
  };

  handleConfirm = () => {
    Modal.error({
      title: messages('request-1.key751')/*导出失败*/,
      content: messages('request-1.key752')/*导出数据已超过上限10000条，请重新选择后再次导出！*/,
    });
  }

  render() {
    const { tab, columns, columnsDining, searchForm, pagination } = this.state;
    const { hotelTypeData, participantRuleCode, externalParticipantRuleCode, multiConsolidatedRuleCode,
      multiConsolidatedRuleAmount, multiIndividualRuleCode, isTenant, hotelConfigData, searchParams
    } = this.state;
    const exportType = {
      'flight': 'TRAVEL_RULE_FLIGHT_EXPORT_TYPE',
      'train': 'TRAVEL_RULE_HOTEL_EXPORT_TYPE',
      'hotel': 'TRAVEL_RULE_TRAIN_EXPORT_TYPE',
    };
    const fileName = {
      'flight': messages('request-1.key753')/*机票差旅标准*/,
      'train': messages('request-1.key754')/*火车差旅标准*/,
      'hotel': messages('request-1.key755')/*酒店差旅标准*/,
    }
    const exportList = [
      {
        title: messages('request-1.key756')/*导出全部*/,
        key: 'all',
        exportType: exportType[tab],
        exportCommand: exportType[tab],
        searchParams: {
          page: 0,
          size: 10000,
          travelType: searchParams.travelType,
        },
      },
      {
        title: messages('request-1.key757')/*导出当前页*/,
        key: 'now',
        exportType: exportType[tab],
        exportCommand: exportType[tab],
        searchParams,
      },
    ];
    const menuExport = (
      <Menu>
        {
          exportList.map((item)=>{
            return(
              <Menu.Item key={item.key}>
                {pagination.total > 10000 ?
                  <div onClick={this.handleConfirm} style={{ display: "inline-block" }}>
                   {messages('request-1.key758')/*导出*/}
                  </div> : <ExportModal
                    key={item.exportType}
                    exportTitle={item.title}
                    exportType={item.exportType}
                    exportCommand={item.exportCommand}
                    exportCondition={{ travelRuleParam: item.searchParams }}
                  />
                }
              </Menu.Item>
            )
          })
        }
      </Menu>
    );
    return (
      <div className="full-height-page full-page-margin" style={{height: 'calc(100vh - 110px)'}}>
        <Tabs activeKey={tab} onChange={this.handleTabChange}>
          <TabPane tab={messages('request-1.key474')/*机票*/} key="flight" />
          <TabPane tab={messages('request-1.key283')/*火车*/} key="train" />
          <TabPane tab={messages('request-1.key285')/*酒店*/} key="hotel" />
          <TabPane tab={messages('request-1.key495')/*用车*/} key="car" />
          <TabPane tab={messages('request-1.key508')/*用餐*/} key="dining" />
        </Tabs>
        {tab && (
          <SimpleTable
            columns={tab === 'dining' ? columnsDining : columns}
            searchForm={searchForm}
            service={this.service}
            rowKey="id"
            onRow={record => ({
              onClick: () => this.handleRowClick(record)
            })}
            onGetData={(data, pagination) => {this.setState({ pagination })}}
            onRef={ref => this.simpleTableRef = ref}
            tableName='travel-standard-list'
            expandAll
          >
            <div style={{position: 'relative'}}>
              {tab === 'hotel' && (
                <div>
                  <div className="header-title" style={{marginBottom: '12px'}}>
                    {messages('request-1.key750')/*差标规则*/}
                    {isTenant && (
                      <Button type="primary" onClick={this.handleEditHotelConfig} style={{position: 'absolute', right: 0}}>
                        {messages('common.edit')/*编辑*/}
                      </Button>
                    )}
                  </div>
                  <Row className="custom-form-row">
                    <Col span={8}>
                      <div className="field-name">{messages('request-1.key738')/*内部参与人多条标准时：*/}</div>
                      <div className="field-content">{hotelConfigData.participantRuleName}</div>
                    </Col>
                    <Col span={8}>
                      <div className="field-name">{messages('request-1.key739')/*外部参与人标准：*/}</div>
                      <div className="field-content">{hotelConfigData.externalParticipantRuleName}</div>
                    </Col>
                    <Col span={8}>
                      <div className="field-name">{messages('request-1.key740')/*多个参与人统一订票时：*/}</div>
                      <div className="field-content">{hotelConfigData.multiConsolidatedRuleName}</div>
                    </Col>
                  </Row>
                  <Row className="custom-form-row">
                    <Col span={8}>
                      <div className="field-name">{messages('request-1.key741')/*统一订票合住加权系数：*/}</div>
                      <div className="field-content">{multiConsolidatedRuleAmount}%</div>
                    </Col>
                    <Col span={8}>
                      <div className="field-name">{messages('request-1.key742')/*多个参与人各自订票时：*/}</div>
                      <div className="field-content">{hotelConfigData.multiIndividualRuleName}</div>
                    </Col>
                  </Row>
                </div>
              )}
              <Space>
                <Button type="primary" onClick={this.handleNew}>
                  {tab !== 'dining' ? messages('request-1.key747')/*新建标准*/ : messages('request-1.key749')/*新建类型*/}
                </Button>
                {(tab === 'train' || tab === 'flight' || tab === 'hotel') &&
                <span>
                  <Importer
                    modalOptions={{
                      title: messages('request-1.key759')/*初始化导入*/,
                      afterClose: () => this.setState({ showImportModal: false })
                    }}
                    onOk={this.importOfferFile}
                    templateOptions={{
                      templateList: [{
                        downloadUrl: `/api/travel/rule/template/export${'?travelType=' + searchParams.travelType}`, //模板下载地址
                        downFileName: messages('request-1.key760')/*差标导入模版*/, //模板下载后文件名
                        templateName: fileName[tab], //模板显示文件名
                        downFileExtension: 'xlsx' //模板后缀
                      }]
                    }}
                    uploadOptions={{
                      uploadUrl: '/api/travel/rule/import',
                      listenUrl: '/api/batch/transaction/logs/travel/rule',
                      uploadParams: { travelType: searchParams.travelType }
                    }}
                    uploadResultOptions={{
                      shouldDownloadErrorInfo: true,
                      showErrorTable: true,
                      errorParams: { travelType: searchParams.travelType },
                      errorUrl: '/api/travel/rule/failed/export',
                      getErrorTableVisible: result => result && result.failureEntities > 0
                    }}
                    btnProps={{
                      style: {marginRight: '8px'}
                    }}
                  />
                  <Dropdown overlay={menuExport}>
                    <Button>{messages('request-1.key761')/*导出数据*/}<Icon type="down"/></Button>
                  </Dropdown>
                </span>}
              </Space>
            </div>
          </SimpleTable>
        )}
      </div>
    )
  }
}


TravelStandard.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission
  }
}

export default connect(mapStateToProps)(TravelStandard)
